var fountainInit = function() {

	var fountainServer = monicaServer({
		serverName: 'narrabri.ozforecast.com.au'
	});
	
	var fountainRef = null;
	
	var serverConnected = function(serverName) {
		// Get the state of the fountain.
		var fountainPoints = ['home.irrigation.birdbath'];
		var pointRefs = fountainServer.addPoints(fountainPoints);
		pointRefs[0].addCallback(fountainUpdate);
		fountainRef = pointRefs[0];
		
		fountainServer.getDescriptions();
		fountainServer.startUpdating();
	};
	
	var fountainUpdate = function(pointRef) {
		// Write the state out.
		var value = pointRef.latestValue();
		console.log(value.value);
		if (value.value === 'false') {
			dojo.attr('fountainState', 'innerHTML', 'OFF');
			dojo.removeClass('fountainState', 'fountainOn');
			dojo.attr('fountainChanger', 'innerHTML', 'Turn it ON');
		} else {
			dojo.attr('fountainState', 'innerHTML', 'ON');
			dojo.addClass('fountainState', 'fountainOn');
			dojo.attr('fountainChanger', 'innerHTML', 'Turn it OFF');
		}
		// Update the image.
		imageShow();
	};
	
	fountainServer.connect().then(serverConnected);

	// Connect the button.
	dojo.connect(dojo.byId('fountainChanger'), 'onclick', function() {
		// Get the current state.
		var currState = fountainRef.latestValue();
		var newState = {
			type: 'bool',
			user: 'user',
			pass: 'pass'
		};
		if (currState.value === 'false') {
			newState.value = true;
		} else {
			newState.value = false;
		}
		fountainRef.setValue(newState);
	});
	
	// Show the image.
	var imageShow = function() {
		var imageContainer = dojo.byId('fountainImage');
		var fountainImage = dojo.create('img', {
			src: 'http://narrabri.ozforecast.com.au:9001/snapshot.cgi' +
					'?user=admin&pwd='
		});
		dojo.place(fountainImage, imageContainer, 'only');
	};
	
};

dojo.addOnLoad(fountainInit);